import React, { Component, } from 'react';
import { StyleSheet, Text, View, Clipboard, ScrollView, Picker, Image, TextInput, AsyncStorage, } from 'react-native';
import { POST, } from '../../commons/utils/request';
import { dealInAccountInfo, } from '../../app/constants/urls';
import Toast from '../../components/Toast';
import urls from '../../app/constants/urls';
import {informConfig, pageConfig, findItemConfig} from './config'
import ImagePicker from '../account/components/ImagePicker';
import { Form, } from '../account/components/common-ui/Form';
import { registerAnimation } from 'react-native-animatable';

const styles = StyleSheet.create({
  container:
  {
    flex: 1,
    backgroundColor: '#FFFFFF',
    paddingLeft: 20,
    paddingRight: 20,
    paddingTop: 10,
  },

  titleContainer:
  {
    flexDirection: "row",
    backgroundColor: '#FFFFFF',
    paddingTop: 15,
    paddingBottom: 15,
  },
  devideLine:{
    height: 0.5,
    backgroundColor: '#E5E5E5',
  },
  txtTitle:{
    fontSize: 14,
    textAlign: 'left',
    color: '#696B79',
    flex: 2,
  },
  txtTitleOther:{
    fontSize: 14,
    textAlign: 'left',
    color: '#A3A4A7',
    backgroundColor: '#F7F8FA',
    flex: 1000,
    paddingTop: 15,
    paddingBottom: 15,
  },
  txtHint:{
    fontSize: 14,
    textAlign: 'right',
    justifyContent: 'flex-end',
    color: '#C3C3C3',
    flex: 5,
  },
  input: {
    height: 40,
    fontSize: 14,
    textAlign: 'right',
    flex: 5,
    marginTop: -10,
  },
  txtHintHight:{
    fontSize: 14,
    textAlign: 'right',
    justifyContent: 'flex-end',
    color: '#696B79',
    flex: 5,
  },
  rightArrow:{
    width: 22,
    height: 22,
  },
  txtChoose:{
    fontSize: 14,
    textAlign: 'center',
    color: '#696B79',
    backgroundColor: '#E5E5E5',
    paddingBottom:10,
    paddingTop: 10,
  },
  txtNotify: {
    textAlign: "center",
    color: '#FFFFFF',
    backgroundColor: '#0091ff',
    marginTop: 30,
    marginBottom: 30,
    paddingTop: 12,
    paddingBottom: 12,
    fontSize: 14,
    borderRadius: 6,
  },
  txtUpload:{
    fontSize: 14,
    textAlign: 'left',
    marginTop: 30,
    color: '#696B79',
    flex: 2,
  },
});

export default class Inform extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showMoneyType: false,
      showReceiverType: false,
      showUse: false,
      showRelationship: false,
      amount: '',
      firstName: '',
      lastName: '',
      fileId: 0,
      currencyType: -1,
      dealUserType: -1,
      useType: -1,
      userRelationType: -1,
      dealUserCountryCode: -1,
    };
  }

  static navigationOptions = ({ navigation, }) => ({
    headerTitle: '通知银行收款',
  });

  async componentDidMount() {
    await AsyncStorage.setItem('listStatus', "0");
  }

  renderNotify() {
    return (
      <View>
        <Text style={styles.txtNotify}  
          onPress={() => {
            this.notifySystem();
          }}
        >提交通知</Text>
      </View>
    )
  }

  notifySystem() {
    let params = this.props?.navigation?.state?.params
    console.log('TAGGG','==========notifySystem=====params===' + JSON.stringify(params))
    const param = {
      bankCard: params.bankCard,
      dealAmount: this.state.amount,
      dealProveFileId: [this.state.fileId],
      dealUserCountryCode: -1,
      dealUserFamilyName: this.state.firstName,
      dealUserGivenName: this.state.lastName,
      currencyType: this.state.currencyType || 1, // TODO
      dealUserType: this.state.dealUserType || 1, // TODO
      useType: this.state.useType,
      userRelationType: this.state.userRelationType,
    }
    POST(urls.dealInSubmit, JSON.stringify(param)).then(resp => {
      console.log('TAGGG', `dealInAccountInfo====resp==${JSON.stringify(resp)}`);
      if (resp && resp.code === 0) {
        Toast.show({ title: "通知银行成功", });
        this.props.navigation.navigate('InWard', param);
      } else {
        Toast.show({ title: "通知失败, " + resp.msg, })
      }
    }, error => {
      Toast.show({ title: "系统异常, 请稍后再试", })
    });
  }
  render() {
    const items = []
    pageConfig.forEach((item, i) => {
      view = this.renderItem(item)
      items.push(view)
    })
    return (
      <View style={styles.container}>
        <ScrollView>
          {items}
          {this.renderUploadFile()}
          {this.renderNotify()}
        </ScrollView>
      </View>
    );
  }

  renderUploadFile() {
    return (
      <View style ={styles.titleContainer}>
        <Text style={ styles.txtUpload}>汇款凭证</Text>
        <ImagePicker 
          OnImageId={(id) => {
            this.setState({fileId: id})
          }} 
        />
      </View>
    )
  }

  _setState(stateKey, show, value) {
    if (stateKey == 'showMoneyType') {
      const id = findItemConfig(informConfig.moneyType, value)
      console.log('TAGGG', '===_setState==findItemConfig=showMoneyType=id=' + id)
      this.setState({showMoneyType: show, currencyType: id})
    } else if (stateKey == 'showReceiverType') {
      const id = findItemConfig(informConfig.remittanceType, value)
      console.log('TAGGG', '===_setState==findItemConfig====showReceiverType===id===' + id)
      this.setState({showReceiverType: show, dealUserType: id})
    } else if (stateKey == 'showUse') {
      const id = findItemConfig(informConfig.useInfo, value,)
      console.log('TAGGG', '===_setState==findItemConfig===showUse==id=' + id)
      this.setState({showUse: show, useType: id})
    } else if (stateKey == 'showRelationship') {
      const id = findItemConfig(informConfig.relationship, value)
      console.log('TAGGG', '===_setState==findItemConfig=relationship=id=' + id)
      this.setState({showRelationship: show, userRelationType: id})
    } else if (stateKey == 'amount') {
      this.setState({amount: value})
    } else if (stateKey == 'firstName') {
      this.setState({firstName: value})
    } else if (stateKey == 'lastName') {
      this.setState({lastName: value})
    } else if (stateKey == 'fileId') {
      this.setState({fileId: value})
    } 
  }

  chooseCity(itemData) {
    console.log('TAGGG', '===chooseCity======')
    // await AsyncStorage.setItem('listStatus', "0");
    this.props.navigation.navigate('Country', { pageMode: 1, callback: (element) => {
      console.log('TAGGG', '===chooseCity==callback====' + JSON.stringify(element))
      itemData.choosedData = element.name || element.countryName
      this.setState({dealUserCountryCode: element.code})
    }, });
  }

  renderItem(itemData) {
    const views = []
    itemData.chooseData.forEach((item, index) => {
      const view = (
        <Text 
          style={styles.txtChoose}
          onPress={()=>{
            itemData.choosedData = item.value
            this._setState(itemData.stateKey, false, item.value)
          }}>
            {item.value}
        </Text>)
      views.push(view)
    })
    return (
      <View>
        <View style={styles.titleContainer}>
            <Text style={itemData.type == 3 ? styles.txtTitleOther : styles.txtTitle}>{itemData.title}</Text>
            {
              itemData.type == 1 || itemData.type == 4 ?
              <Text 
                style={itemData.choosedData ? styles.txtHintHight : styles.txtHint} 
                onPress={()=>{
                  console.log('TAGGG', '==onPress=itemData======' + JSON.stringify(itemData))
                  if(itemData.type == 4) {
                    console.log('TAGGG', '==onPress=chooseCity===itemData.type == 4===')
                    this.chooseCity(itemData)
                  } else {
                    this._setState(itemData.stateKey, !this.state[itemData.stateKey], null)
                  }     
                }}>
                {itemData.choosedData ? itemData.choosedData : itemData.hint}
              </Text>
              :
              <TextInput
                style={styles.input}
                placeholder={itemData.hint}
                placeholderTextColor="#696B79"
                onChangeText={(name) => this._setState( itemData.stateKey, false, name)}
              />
            }
            {itemData.type == 1 || itemData.type == 4 ? <Image resizeMode="contain" style={styles.rightArrow} source={{ uri : 'http://120.48.109.211:8088/static/icon/right.png', }} /> : <View/>}
        </View>
        {this.state[itemData.stateKey] ? views : <View/>}
        {itemData.showBottomLine ? <View style={styles.devideLine}></View> : <View/>}
      </View>     
    )  
  }
}
